package com.kai.common.data;

import com.kai.common.exception.ErrorCode;
import com.kai.common.exception.ErrorCodeConstants;
import lombok.AccessLevel;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.FieldDefaults;

import java.io.Serializable;

/**
 * 统一返回结果
 * 
 * @param <T>
 */
@Data
@FieldDefaults(level = AccessLevel.PRIVATE)
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class Result<T> implements Serializable {

    private static final long serialVersionUID = -8676181355403088497L;

    /**
     * 调用是否正常
     */
    boolean success;

    /**
     * 返回对象
     */
    T body;

    /**
     * 返回码，错误码
     */
    int code;

    /**
     * 返回消息
     */
    String msg;

    public Result(T body, int code, String msg, boolean success) {
        this.body = body;
        this.code = code;
        this.msg = msg;
        this.success = success;
    }

    public static <T> Result<T> fail() {
        return fail(ErrorCodeConstants.BASE_ERROR);
    }

    public static <T> Result<T> fail(ErrorCode errorCode) {
        return fail(errorCode.getCode(), errorCode.getMsg());
    }

    public static <T> Result<T> fail(int code, String message) {
        return new Result<>(null, code, message, false);
    }

    public static<T> Result<T> success() {
        return success(null);
    }

    public static<T> Result<T> success(T data) {
        return new Result<>(data, ErrorCodeConstants.SUCCESS.getCode(), ErrorCodeConstants.SUCCESS.getMsg(), true);
    }
}
